<script>
// 引用地址
import Api from './http/api.js'; // 引入接口地址文件
import Store from './utils/store.js'; // 引入存取删除缓存数据
import Sign from './utils/sign.js'; // 引入签名文件
import Request from './http/request.js'; // 设置拦截 get post

// 小程序配置公用组件
import config from './env/index.js'; // 引入小程序配置文件

const env = 'remote'; // 测试 remote  开发 deployment   local
const Appname = '杭州国控电力科技有限公司';
const AppVersion = '1.3.0'; // 开发版本

App.version = '1.3.0'; //开发版本
App.config = config[env]; //根据环境变量获取对应的配置信息
App.config.env = env;
App.config.chargeApi = config.chargeApi;

export default {
  data() {
    return {};
  },
  globalData: {
    userId: '',
    version: AppVersion,
    themeColor: '#FF8100',
    themeSecondColor: '#FF7200',

    Api,
    Store,
    Sign,
    Appname,
    config: config[env],
    get: Request.fetch,

    post: async (url, data, option = {}) => {
      option.method = 'post';
      try {
        return await Request.fetch(url, data, option);
      } catch (error) {
        console.error('POST request error:', error);
      }
    },

    updateLastTime: async function (user_id) {
      if (user_id) {
        const signObject = { user_id };
        const signvalue = Sign.signutil(signObject);
        try {
          const res = await this.get(Api.updateLastTime, { user_id, sign: signvalue });
          console.log(res);
        } catch (e) {
          console.error('Error updating last time:', e);
        }
      }
    },

    appGetOpenId: async function () {
      if (!Store.getItem('token')) {
        try {
          const res = await uni.login();
          if (res.code) {
            const signObject = { code: res.code };
            const signvalue = Sign.signutil(signObject);
            const response = await this.get(Api.getSession, { code: res.code, sign: signvalue });
            Store.setItem('token', response.token);
            return response.token;
          }
        } catch (error) {
          console.error('Error getting openId:', error);
        }
      }
    },

    clickCheckLogin: async function (e) {
      console.log('e:', e);
      let token = Store.getItem('token') || await this.appGetOpenId();
      const { signature, userInfo, rawData } = e.detail;
      const signObject = {
        signature,
        rawData: encodeURIComponent(rawData),
        token,
        avatarUrl: userInfo.avatarUrl,
        city: userInfo.city,
        country: userInfo.country,
        gender: userInfo.gender,
        language: userInfo.language,
        nickName: encodeURIComponent(userInfo.nickName),
        province: userInfo.province
      };
      const signvalue = Sign.signutil(signObject);
      try {
        const res = await this.get(Api.login, { ...signObject, sign: signvalue });
        console.log(res);
        if (res.userId) {
          this.readyToPay(res.userId);
        } else {
          console.log('登录失败！');
        }
      } catch (e) {
        console.error('Login error:', e);
      }
    },

    readyToPay: function (user_id) {
      const paySource = Store.getItem('pay_source');
      console.log(paySource);
      Store.setItem('user_id', user_id);
      Store.setItem('ifLogged', true);

      const routes = {
        TABBAR_MINE: '../sysUserInfo/sysUserInfo',
        TABBAR_ORDERLIST: '../orderList/orderList',
        FROM_TID_OLD: `../tidOLDSelMoney/tidOLDSelMoney?device_code=${Store.getItem('device_code')}`,
        FROM_TID_NEW: `../tidNEWSelMoney/tidNEWSelMoney?device_code=${Store.getItem('device_code')}`,
        FROM_DPC: `../tidDPCSelMoney/tidDPCSelMoney?device_code=${Store.getItem('device_code')}`
      };

      const url = routes[paySource];
      if (url) {
        paySource.startsWith('FROM_') ? uni.redirectTo({ url }) : uni.switchTab({ url });
      }
    }
  },
  onLaunch: function () {
    this.globalData.appGetOpenId();
    this.globalData.updateLastTime(Store.getItem('user_id'));
  }
};
</script>
<style>
@import "./app.css";
</style>
